package com.weijing.pretty_app.adapter

import android.Manifest
import android.bluetooth.BluetoothDevice
import android.content.pm.PackageManager
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat.checkSelfPermission
import androidx.recyclerview.widget.RecyclerView
import com.weijing.pretty_app.R
import com.weijing.pretty_app.databinding.ItemBluetoothBinding

class DevicesAdapter : RecyclerView.Adapter<DevicesAdapter.DevicesHolder>() {

    private val list = mutableListOf<BluetoothDevice>()
    private var deviceAddressId: String? = null

    fun updateDevices(newDevices: List<BluetoothDevice>) {
        list.clear()
        list.addAll(newDevices)
        notifyDataSetChanged()
    }

    fun noticeAddress(addressId: String) {
        deviceAddressId = addressId
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DevicesHolder {
        return DevicesHolder(
            ItemBluetoothBinding.inflate(
                LayoutInflater.from(parent.context), parent, false
            )
        )
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: DevicesHolder, position: Int) {
        val device = list[position]
        with(holder) {
            val deviceName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (checkSelfPermission(
                        binding.itemBluetoothTv1.context, Manifest.permission.BLUETOOTH_CONNECT
                    ) == PackageManager.PERMISSION_GRANTED
                ) {
                    device.name ?: "未知设备"
                } else {
                    "权限不足"
                }
            } else {
                device.name ?: "未知设备"
            }

            if (deviceAddressId == device.address) {
                binding.itemBluetoothIv.visibility = View.VISIBLE
            } else {
                View.GONE
            }

            binding.itemBluetoothTv1.text = deviceName
            binding.itemBluetoothTv2.text = device.address
            val state = device.bondState
            if (state == BluetoothDevice.BOND_BONDED) {
                binding.itemBluetoothView.setBackgroundResource(R.color.color_1afa29)
            } else {
                binding.itemBluetoothView.setBackgroundResource(R.color.color_00C1CD)
            }

            if (onClickListener != null) {
                holder.itemView.setOnClickListener {
                    onClickListener?.onItemClickListener(device)
                }
            }
        }
    }

    class DevicesHolder(val binding: ItemBluetoothBinding) : RecyclerView.ViewHolder(binding.root)

    var onClickListener: OnClickListener? = null

    interface OnClickListener {
        fun onItemClickListener(device: BluetoothDevice)
    }
}